<?php
namespace app\erp\model;

use think\Model;
use traits\model\SoftDelete;
use app\erp\validate\Departmentrule;
use think\Cache;

class Departmentdb extends Model
{
    use SoftDelete;

    protected $deleteTime = 'delete_time';

    protected $pk = 'department_id';

    protected $name = 'department';

    protected $type = [
        'create_time' => 'timestamp:Y-m-d',
        'delete_time' => 'timestamp:Y-m-d'
    ];

    protected $autoWriteTimestamp = true;

    protected $insert = [
        'partner_id' => PARTNER_ID,
        'site_id'
    ];

    protected function setSiteIdAttr($value)
    {
        if (! $value) {
            return SITE_ID;
        }
        if ($value == 0) {
            return null;
        }
        if ($value == - 1) {
            return null;
        }
        return $value;
    }

    public $param = array();

    protected function cache_name($name)
    {
        $new_arr = $this->param;
        $new_arr['partner_id'] = PARTNER_ID;
        if (! isset($new_arr['site_id'])) {
            $new_arr['site_id'] = SITE_ID;
        }
        ksort($new_arr);
        $param_str = http_build_query($new_arr);
        return md5($name . $param_str);
    }
    // 基础查询
    public function base($query)
    {
        $field = $this->getDeleteTimeField(true);
        if ($field) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->onlyTrashed();
            } else {
                $query->useSoftDelete($field);
            }
        }
        $query->where('partner_id', PARTNER_ID);
        if (! empty(SITE_ID)) {
            $query->where('site_id', SITE_ID);
        }
    }
    // 查询分站
    public function scopeSiteId($query, $siteId)
    {
        if ($siteId > 0) {
            $query->where('site_id', $siteId);
        } else {
            $query->where('site_id', 'EXP', 'IS NULL');
        }
    }
    // 查询名称
    public function scopeDepartmentName($query, $departmentName)
    {
        $query->where('department_name', 'like', '%' . $departmentName . '%');
    }
    
    // 查询列表
    public function ajaxSelect()
    {
        if (isset($this->param['department_name']) && ! empty($this->param['department_name'])) {
            $this->departmentName($this->param['department_name']);
        }
        if (isset($this->param['site_id']) && ! empty($this->param['site_id'])) {
            $this->siteId($this->param['site_id']);
        }
        $data = $this->order($this->param['_o'], $this->param['_b'])
            ->cache($this->cache_name('department_select'), 86400, 'department')
            ->page($this->param['page'], $this->param['limit'])
            ->select();
        $count = $this->count();
        if (! $data->isEmpty()) {
            $data = $data->toArray();
            foreach ($data as $key => $val) {
                $data[$key] = $this->handleData($val);
            }
        }
        $return['data'] = $data;
        $return['count'] = $count;
        return $return;
    }

    /**
     *
     * @todo 获取详情
     */
    public function ajaxFind($department_id)
    {
        if (empty($department_id)) {
            $data['department_name'] = '会员';
            return $data;
        } elseif ($department_id == - 1) {
            $data['department_name'] = '站点管理员';
            return $data;
        } else {
            $data = $this->where('department_id', $department_id)->find();
            $data = $data->toArray();
            $data = $this->handleData($data);
            return $data;
        }
    }

    /**
     *
     * @todo 保存数据
     */
    public function ajaxSave($param)
    {
        $rule = new Departmentrule();
        $param['partner_id'] = PARTNER_ID;
        $param['site_id'] = SITE_ID;
        if (! $rule->check($param)) {
            return $rule->getError();
        }
        unset($param['partner_id']);
        unset($param['site_id']);
        if (isset($param['department_id']) && $param['department_id'] != '') {
            $department_id = $param['department_id'];
            unset($param['department_id']);
            $this->save($param, [
                'department_id' => $department_id
            ]);
        } else {
            $this->allowField(true)->save($param);
        }
        Cache::clear('department');
        return 'success';
    }
    // 软删除
    public function ajaxDelete()
    {
        if (isset($this->param['department_id'])) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->destroy(function ($query) {
                    $query->where('department_id', 'IN', $this->param['department_id']);
                }, true);
            } else {
                $this->destroy(function ($query) {
                    $query->where('department_id', 'IN', $this->param['department_id']);
                }, true);
            }
            Cache::clear('department');
        }
    }
    // 恢复数据
    public function ajaxRestore()
    {
        if (isset($this->param['department_id'])) {
            $map[$this->pk] = array(
                'IN',
                $this->param['department_id']
            );
            $this->restore($map);
            Cache::clear('department');
        }
    }
    // 数据处理
    protected function handleData($val)
    {
        $sitedb = new Sitedb();
        foreach ($val as $k => $v) {
            $val[$k] = $v;
            switch ($k) {
                case 'site_id':
                    $site_info = $sitedb->ajaxFind($v);
                    $val['site_id_text'] = $site_info['site_name'];
                    break;
                default:
                    break;
            }
        }
        return $val;
    }
}